package team.nmsg.ge.system.init.jpa;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder.Builder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

//@Configuration
//@EnableTransactionManagement
//@EnableJpaRepositories(entityManagerFactoryRef="entityManagerFactoryPrimary"
//,transactionManagerRef="transactionManagerPrimary",basePackages= { "com.bdcom.nmsweb" } )
public class JPAOrmConfig {

	@Autowired
	@Qualifier("DataSource")
	private DataSource primaryDataSource;

	@Primary
	@Bean(name = "entityManagerPrimary")
	public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
		
		EntityManager em = entityManagerFactoryPrimary(builder).getObject().createEntityManager();
		return em;
	}

	@Primary
	@Bean(name = "entityManagerFactoryPrimary")
	public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(
			EntityManagerFactoryBuilder builder) {
		
		 Builder b2 = builder.dataSource(primaryDataSource)
				.properties(getVendorProperties(primaryDataSource));
//				.packages("team.nmsg")
//				.persistenceUnit("nmsweb_model-2.0.jar");
				
				
		 LocalContainerEntityManagerFactoryBean build = b2.build();
		 build.setPackagesToScan("team.nmsg");
		 
		 
		 return build;
	}

	@Autowired
	private JpaProperties jpaProperties;

	private Map<String, String> getVendorProperties(DataSource dataSource) {
		return jpaProperties.getHibernateProperties(dataSource);
	}

	@Primary
	@Bean(name = "transactionManagerPrimary")
	public PlatformTransactionManager transactionManagerPrimary(
			EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(entityManagerFactoryPrimary(builder)
				.getObject());
	}
}